import base64
import json

import faker
from locust import FastHttpUser, task, between, run_single_user, constant, events, tag,constant_pacing,User


username = open('../cookies.txt', mode='r', encoding='utf8')

def enconde_bs64(data):
    data = json.dumps(data)
    encode64 = base64.b64encode(data.encode('utf-8'))
    return encode64.decode('utf-8')

def decode64_str(data):
    decode64 = base64.b64decode(data)
    decode64_str = decode64.decode('utf-8')
    return decode64_str



class UserDeviceTask(FastHttpUser):
    host = "https://www.retone-hearing.fit"
    # wait_time = between(1, 5)
    # wait_time = constant(1)

    # abstract = True
    def on_start(self):
        self.cookie = next(username).strip()
        # print(self.cookie)
        self.header = {"Cookie": f"hearingaid_user={self.cookie}", "Content-Type": "application/json"}

    @task
    def bind_set(self):

        # 绑定指定的设备
        url = '/platformRetoneFit/api/deviceBinding/needAppUserAuth/responseEncode/requestDecode/binding'
        data = {
                "deviceNumber": f"{str(self.cookie)}",
                "deviceName": "测试设备2",
                "deviceTypeCode": "1",
                "chipTypeCode": "1"
        }
        # print(self.header)
        with self.rest('post', url, data=enconde_bs64(data), headers=self.header) as resp:
            if resp.status_code != 200 or (resp.js['data'] is None and resp.js['description'] is not None):
                resp.failure(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
            else:
                # print(resp.json())
                resp.success()

    @task
    def device_info(self):
        # 获取用户的绑定信息
        url = '/platformRetoneFit/api/deviceBinding/needAppUserAuth/responseEncode/requestDecode/getDeviceBindingList'
        with self.rest('post', url, headers=self.header) as resp:
            if resp.status_code != 200 or (resp.js['data'] is None and resp.js['description'] is not None):
                resp.failure(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
            else:
                print(resp.json())
                resp.success()

    @task
    def check_device_is_bind(self):
        # 检查设备是否可以绑定
        url = '/platformRetoneFit/api/deviceBinding/needAppUserAuth/responseEncode/requestDecode/checkDeviceBinding'

        data = {
            "deviceNumber": "71ab434"
        }
        with self.rest('post', url, data=enconde_bs64(data), headers=self.header) as resp:
            if resp.status_code != 200 or (resp.js['data'] is None and resp.js['description'] is not None):
                resp.failure(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
            else:
                resp.success()

    @task
    def userdevice(self):
        # 使用设备
        url = '/platformRetoneFit/api/deviceBinding/needAppUserAuth/responseEncode/requestDecode/deviceUse'

        data = {
            "leftDevice": {
                "deviceNumber": f"{str(self.cookie)}",
                "firmwareVersion": "1.0.38"
            },
            "rightDevice": {
                "deviceNumber": f"{str(self.cookie)}",
                "firmwareVersion": "1.0.38"
            }
        }
        with self.rest('post', url, data=enconde_bs64(data), headers=self.header) as resp:
            if resp.status_code != 200 or (resp.js['data'] is None and resp.js['description'] is not None):
                if resp.js['description'] == '该设备未被绑定，请先绑定':
                    print(resp.js)
                    resp.success()
                else:
                    resp.failure(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
            else:
                resp.success()

    # @task(1)
    # @task
    # def unbound(self):
    #     # 解除绑定设备
    #     url = '/platformRetoneFit/api/deviceBinding/needAppUserAuth/responseEncode/requestDecode/unbound'
    #     data = {
    #         "deviceNumberList": ['789468416545646']
    #     }
    #     with self.rest('post', url, data=enconde_bs64(data), headers=self.header) as resp:
    #         if resp.status_code != 200 or (resp.js['data'] is None and resp.js['description'] is not None):
    #             resp.failure(f"=======错误返回:status_code={resp.status_code},resp={resp.text}==========")
    #         else:
    #             resp.success()
    #             # print(resp.json())



if __name__ == '__main__':
    run_single_user(UserDeviceTask)